package com.example.a_java.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a_java.common.Result;
import com.example.a_java.dto.ContractSignDTO;
import com.example.a_java.entity.LoanContract;
import com.example.a_java.service.LoanContractService;
import com.example.a_java.util.ExcelUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 贷款合同Controller
 */
@Tag(name = "合同管理", description = "合同管理相关接口")
@RestController
@RequestMapping("/contract")
@SecurityRequirement(name = "bearer-key")
public class LoanContractController {

    @Autowired
    private LoanContractService contractService;

    /**
     * 获取合同列表
     */
    @Operation(summary = "获取合同列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('loan:contract:list')")
    public Result<Page<LoanContract>> list(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "合同编号") @RequestParam(required = false) String contractNo,
            @Parameter(description = "客户ID") @RequestParam(required = false) Long custId,
            @Parameter(description = "合同状态") @RequestParam(required = false) Integer contractStatus) {
        
        Page<LoanContract> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LoanContract> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.like(StringUtils.hasText(contractNo), LoanContract::getContractNo, contractNo)
                .eq(custId != null, LoanContract::getCustId, custId)
                .eq(contractStatus != null, LoanContract::getContractStatus, contractStatus)
                .orderByDesc(LoanContract::getCreateTime);
        
        contractService.page(page, wrapper);
        return Result.success(page);
    }

    /**
     * 获取合同详情
     */
    @Operation(summary = "获取合同详情")
    @GetMapping("/{contractId}")
    @PreAuthorize("hasAuthority('loan:contract:query')")
    public Result<LoanContract> getInfo(@PathVariable Long contractId) {
        return Result.success(contractService.getById(contractId));
    }

    /**
     * 获取合同详情
     */
    @Operation(summary = "下载合同详情")
    @GetMapping("/down/{contractId}")
    @PreAuthorize("hasAuthority('loan:contract:query')")
    public void getInfoFile(@PathVariable Long contractId, HttpServletResponse response) throws UnsupportedEncodingException {
        LoanContract loanContract = contractService.getById(contractId);
        List<LoanContract> o1 = new ArrayList<>();

        if (loanContract != null) {
            System.out.println(loanContract); // 打印以检查数据
            o1.add(loanContract);
        } else {
            // 处理合同未找到的情况
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 设置响应头

        response.addHeader("responseType","blob");
        response.setCharacterEncoding("UTF-8");
        // 导出 Excel
        ExcelUtils.export(response, "详情表", o1, LoanContract.class);
    }



    /**
     * 生成合同
     */
    @Operation(summary = "生成合同")
    @PostMapping("/generate")
    @PreAuthorize("hasAuthority('loan:contract:add')")
    public Result<Boolean> generate(@RequestBody @Valid LoanContract contract) {
        return Result.success(contractService.generateContract(contract));
    }

    /**
     * 更新合同状态
     */
    @Operation(summary = "更新合同状态")
    @PutMapping("/status")
    @PreAuthorize("hasAuthority('loan:contract:edit')")
    public Result<Boolean> updateStatus(@RequestBody LoanContract contract) {
        LoanContract updateContract = new LoanContract();
        updateContract.setContractId(contract.getContractId());
        updateContract.setContractStatus(contract.getContractStatus());
        updateContract.setRemark(contract.getRemark());
        
        return Result.success(contractService.updateById(updateContract));
    }
    
    /**
     * 合同签署
     */
    @Operation(summary = "合同签署")
    @PostMapping("/sign")
    @PreAuthorize("hasAuthority('loan:contract:edit')")
    public Result<Boolean> sign(@RequestBody @Valid ContractSignDTO signDTO) {
        return Result.success(contractService.signContract(signDTO));
    }

    /**
     * 终止合同
     */
    @Operation(summary = "终止合同")
    @PostMapping("/terminate")
    @PreAuthorize("hasAuthority('loan:contract:edit')")
    public Result<Boolean> terminate(@RequestBody LoanContract contract) {
        LoanContract updateContract = new LoanContract();
        updateContract.setContractId(contract.getContractId());
        updateContract.setContractStatus(30); // 30表示已终止
        updateContract.setRemark(contract.getRemark());
        
        return Result.success(contractService.updateById(updateContract));
    }
} 
